package com.funo.wcity.app.service.mail.send;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
/**  
* 发送器  
*/ 
public class MailSender {
	private MailBean mailBean;
	public MailSender(){}
	public MailSender(MailBean mailBean){
		this.mailBean=mailBean;
	}
	/**
	 * 创建邮件消息体
	 */
	public MimeMessage createMimeMessage() throws MessagingException,UnsupportedEncodingException{
		// 判断是否需要身份认证
		MailAuthenticator authenticator = null;
		Properties pro = mailBean.getProperties();
		if (mailBean.isValidate()) {
			// 如果需要身份认证，则创建一个密码验证器
			authenticator = new MailAuthenticator(mailBean.getUserName(),mailBean.getPassword());
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		// 根据session创建一个邮件消息
		MimeMessage mailMessage = new MimeMessage(sendMailSession);
		// 设置邮件基本信息
		setMimeMessageInfo(mailMessage);
		MimeMultipart multipart = null;
		// 创建什么都不含的邮件体（alternative）
		if (mailBean.getContent() != null && mailBean.getContent().length() > 0)
			multipart = createAlternative(multipart);
		// 创建含有内嵌资源的邮件体(related)
		if (mailBean.getResources() != null && mailBean.getResources().size() > 0)
			multipart = createRelated(multipart);
		// 创建含有附件的邮件体（mixed）
		if (mailBean.getFileNames() != null && mailBean.getFileNames().length() > 0)
			multipart = createMixed(multipart);
		// 添加multipart到邮件内容上
		if (multipart == null)
			multipart = createAlternative(multipart);
	    mailMessage.setContent(multipart);
	    mailMessage.saveChanges();
		return mailMessage;
	}
	// 创建什么都不含的邮件体（alternative）
	private MimeMultipart createAlternative(MimeMultipart multipart)
			throws MessagingException {
		multipart = new MimeMultipart("alternative");
		MimeBodyPart html = new MimeBodyPart();
		html.setContent(mailBean.getContent(), "text/html;charset=UTF-8");
		multipart.addBodyPart(html);
		return multipart;
	}

	// 创建含有内嵌资源的邮件体(related)
	private MimeMultipart createRelated(MimeMultipart multipart)
			throws MessagingException {
		MimeBodyPart alternative = new MimeBodyPart();
		alternative.setContent(multipart);
		MimeMultipart related = new MimeMultipart("related");
		related.addBodyPart(alternative);
		// 添加内嵌资源
		related = addResource(related);
		return related;
	}

	// 添加内嵌资源
	private MimeMultipart addResource(MimeMultipart related)
			throws MessagingException {		
		 Iterator it = mailBean.getResources().entrySet().iterator();
		  while (it.hasNext()) {
			  Map.Entry entry = (Map.Entry) it.next();
			  String key =(String)entry.getKey();//格式：aa.jpg
			  String value =(String)entry.getValue();
			  String[] keyAttr=key.split("\\.");
			  MimeBodyPart img = new MimeBodyPart();
			  FileDataSource fds = new FileDataSource(value);
			  img.setDataHandler(new DataHandler(fds));
			  img.setContentID(keyAttr[0]);
			  img.setHeader("Content-ID", "<"+keyAttr[0]+">");
			  img.setFileName(key);
			  related.addBodyPart(img);
		  }
		return related;
	}

	// 创建含有附件的邮件体（mixed）
	private MimeMultipart createMixed(MimeMultipart multipart)
			throws MessagingException, UnsupportedEncodingException {
		MimeBodyPart related = new MimeBodyPart();
		// 添加multipart到邮件内容上
		if (multipart == null)
			multipart = createAlternative(multipart);
		related.setContent(multipart);
		MimeMultipart mixed = new MimeMultipart("mixed");
		mixed.addBodyPart(related);
		// 添加附件
		mixed = addAttachment(mixed);
		return mixed;
	}

	// 添加附件
	private MimeMultipart addAttachment(MimeMultipart mixed)
			throws MessagingException, UnsupportedEncodingException {
		String files[] = mailBean.getFileNames().split(",");
		for (String file : files) {
			MimeBodyPart attachment = new MimeBodyPart();
			FileDataSource fds = new FileDataSource(file);
			attachment.setDataHandler(new DataHandler(fds));
			attachment.setFileName(MimeUtility.encodeText(fds.getName(),
					"UTF-8", "Q"));
			mixed.addBodyPart(attachment);
		}
		return mixed;
	}
	// 设置邮件具体信息
	private void setMimeMessageInfo(MimeMessage message)throws AddressException, MessagingException,UnsupportedEncodingException {
		// 设置发件人
		if (mailBean.getFromAddress()!= null && !"".equals(mailBean.getFromAddress())) {
			message.setFrom(new InternetAddress(encode(mailBean.getFromAddress())));
			message.setSender(new InternetAddress(encode(mailBean.getFromAddress())));
		}
		// 设置收件人
		if (mailBean.getToAddress()!= null && !"".equals(mailBean.getToAddress()))
			message.setRecipients(RecipientType.TO,
					InternetAddress.parse(encode(mailBean.getToAddress())));
		// 设置抄送人
		if (mailBean.getToCc()!= null && !"".equals(mailBean.getToCc()))
			message.setRecipients(RecipientType.CC,
					InternetAddress.parse(encode(mailBean.getToCc())));
		// 设置密送人
		if (mailBean.getToBcc()!= null && !"".equals(mailBean.getToBcc()))
			message.setRecipients(RecipientType.BCC,
					InternetAddress.parse(encode(mailBean.getToBcc())));
		//设置主题
		if (mailBean.getSubject() != null && !"".equals(mailBean.getSubject()))
			message.setSubject(mailBean.getSubject(), "UTF-8");
		//设置邮件发送时间
		message.setSentDate(mailBean.getMailDate());
	}
	
	// 对中文进行编码
	private String encode(String mailadd) throws UnsupportedEncodingException {
		Pattern p = Pattern.compile("(\"(.*?)\" ?<)");// 查找所有("中文"<)的格式
		StringBuffer sb = new StringBuffer();
		Matcher matcher = p.matcher(mailadd);
		while (matcher.find()) {
			matcher.appendReplacement(sb,
					MimeUtility.encodeText(matcher.group(2), "UTF-8", "B")
							+ " <");
		}
		matcher.appendTail(sb);
		return sb.toString();
	}
	/**
	 * 发送邮件
	 */
	public boolean sendMail() {
		try {
			MimeMessage message = createMimeMessage();
			// 发送消息
			Transport.send(message);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return false;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 发送指定邮件体的邮件
	 */
	public boolean sendMail(MimeMessage message){
		// 发送消息
		try {
			Transport.send(message);
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
